package com.agileai.portal.controller.base;

import java.util.List;

import javax.servlet.ServletContext;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.TreeManageHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.DispatchRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.base.MenuBarManage;
import com.agileai.portal.bizmoduler.base.NavigaterManage;
import com.agileai.portal.bizmoduler.base.PtThemeManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.model.MenuBar;
import com.agileai.portal.driver.model.MenuItem;
import com.agileai.portal.driver.model.Theme;
import com.agileai.portal.driver.service.DriverConfiguration;
import com.agileai.portal.driver.service.PortalConfigService;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class MenuBarManageHandler extends TreeManageHandler {
	public MenuBarManageHandler(){
		super();
		this.serviceId = buildServiceId(MenuBarManage.class);
		this.nodeIdField = "MENU_ID";
	}
	protected TreeBuilder provideTreeBuilder(DataParam param){
		MenuBarManage service = this.getService();
		String navId = param.get("NAV_ID");
		param.put("navId",navId);
		List<DataRow> menuRecords = service.findTreeRecords(param);
		TreeBuilder treeBuilder = new TreeBuilder(menuRecords,"MENU_ID","MENU_NAME","MENU_PID");
		treeBuilder.setTypeKey("MENU_TYPE");
		
		this.setAttribute("treeBuilder", treeBuilder);
		
		return treeBuilder;
	}
	@PageAction
	public ViewRenderer focusTab(DataParam param){
		String responseText = FAIL;
		String currentTabId = param.get("currentTabId");
		this.getSessionAttributes().put(MenuBarManageHandler.class.getName()+"currentTabId",currentTabId);
		responseText = SUCCESS;
		return new AjaxRenderer(responseText);
	}
	protected String getTreeSyntax(DataParam param,TreeModel treeModel,StringBuffer treeSyntax){
    	String result = null;
    	try {
    		treeSyntax.append("<script type='text/javascript'>");
    		treeSyntax.append("d = new dTree('d');");
            String rootId = treeModel.getId();
            String rootName = treeModel.getName();
            treeSyntax.append("d.add('"+rootId+"',-1,'"+rootName+"',\"javascript:doRefresh('"+rootId+"')\",null,null,d.icon.folder,d.icon.folder.folderOpen,null);");
            treeSyntax.append("\r\n");
            buildTreeSyntax(treeSyntax,treeModel);
            treeSyntax.append("\r\n");
            treeSyntax.append("document.write(d);");
            treeSyntax.append("\r\n");
            String currentNodeId = this.getAttributeValue(this.nodeIdField);
            String defaultNodeId = provideDefaultNodeId(param);
            if (currentNodeId.equals(defaultNodeId)){
            	treeSyntax.append("d.s(d.getIndex('").append(currentNodeId).append("'));");
                treeSyntax.append("\r\n");            	
            }            
    		treeSyntax.append("</script>");
    		result = treeSyntax.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
    }
	protected void buildTreeSyntax(StringBuffer treeSyntax,TreeModel treeModel){
		List<TreeModel> children = treeModel.getChildren();
		String parentId = treeModel.getId();
        for (int i=0;i < children.size();i++){
        	TreeModel child = children.get(i);
            String curNodeId = child.getId();
            String curNodeName = child.getName();
            if ("F".equals(child.getType())){
            	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:doRefresh('"+curNodeId+"')\",null,null,d.icon.folder,d.icon.folder.folderOpen,null);");
            	treeSyntax.append("\r\n");
            }else{
            	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:doRefresh('"+curNodeId+"')\");");
            	treeSyntax.append("\r\n");
            }
            this.buildTreeSyntax(treeSyntax,child);
        }
    }	
	private PortalConfigService getPortalConfigService(ServletContext servletContext){
		DriverConfiguration driverConfiguration = (DriverConfiguration)servletContext.getAttribute(AttributeKeys.DRIVER_CONFIG);
		return driverConfiguration.getPortalConfigService();
	}
	protected void processPageAttributes(DataParam param) {
		TreeBuilder treeBuilder = (TreeBuilder)this.getAttribute("treeBuilder");
		TreeModel treeModel = treeBuilder.getRootTreeModel();
		
		if (StringUtil.isNullOrEmpty(this.getAttributeValue("MENU_NAME"))){
			String menuBarId = treeModel.getId();
			PortalConfigService portalConfigService = getPortalConfigService(this.getDispatchServlet().getServletContext());
			MenuBar menuBar = portalConfigService.getMenuBar(menuBarId);
			this.setAttribute("MENU_NAME", treeModel.getName());
			this.setAttribute("MENU_CODE", treeModel.getId());
			this.setAttribute("MENU_THEME", menuBar.getThemeId());
			this.setAttribute("MENU_TYPE", treeModel.getType());
			this.setAttribute("MENU_VISIABLE","Y");
		}
		
		this.setAttribute(param, new String[]{"NAV_ID"});
		FormSelect formSelect = FormSelectFactory.create("MENU_TYPE");
		this.setAttribute("MENU_TYPE", formSelect.addSelectedValue(this.getAttributeValue("MENU_TYPE")));
		
		String navId = param.get("NAV_ID");
		NavigaterManage navigaterManage = this.lookupService(NavigaterManage.class);
		DataParam queryParam = new DataParam("NAV_ID",navId);
		DataRow row = navigaterManage.getRecord(queryParam);
		String naviterType = row.stringValue("NAV_TYPE");
		FormSelect themeSelect = new FormSelect();
		themeSelect.setKeyColumnName("THEME_ID");
		themeSelect.setValueColumnName("THEME_NAME");
		PtThemeManage themeManage = this.lookupService(PtThemeManage.class);
		if (MenuBar.Type.LOGIN_BEFORE.equals(naviterType)){
			queryParam = new DataParam("themeType",MenuBar.Type.LOGIN_BEFORE);
		}else if (MenuBar.Type.LOGIN_AFTER.equals(naviterType)){
			queryParam = new DataParam("themeType",MenuBar.Type.LOGIN_AFTER);
		}
		this.setAttribute("isLoginBeforeMenuBar", String.valueOf(MenuBar.Type.LOGIN_BEFORE.equals(naviterType)));
		List<DataRow> records = themeManage.findRecords(queryParam);
		themeSelect.putValue(Theme.EXTEND_THEME_ID, Theme.EXTEND_THEME_NAME);
		themeSelect.putValues(records);
		
		String selectedTheme = this.getAttributeValue("MENU_THEME");
		this.setAttribute("MENU_THEME", themeSelect.addSelectedValue(selectedTheme));
		
		String visiable = this.getAttributeValue("MENU_VISIABLE");
		if (StringUtil.isNullOrEmpty(visiable)){
			visiable = MenuItem.Visiable.visable;
		}
		FormSelect visiableSelect = FormSelectFactory.create("MENU_VISIABLE");
		this.setAttribute("MENU_VISIABLE", visiableSelect.addSelectedValue(visiable));
		
		String target = this.getAttributeValue("MENU_TARGET");
		if (StringUtil.isNullOrEmpty(target)){
			target = MenuItem.Target.SELF;
		}
		FormSelect targetSelect = FormSelectFactory.create("MENU_TARGET");
		this.setAttribute("MENU_TARGET", targetSelect.addSelectedValue(target));
		
		String personalable = this.getAttributeValue("IS_PERSONAL","N");
		FormSelect personalableSelect = FormSelectFactory.create("BOOL_DEFINE");
		this.setAttribute("IS_PERSONAL", personalableSelect.addSelectedValue(personalable));
		
		String mainLayout = getAttributeValue("MAIN_LAYOUT");
		if (StringUtil.isNullOrEmpty(mainLayout)){
			mainLayout = "R";
		}
		setAttribute("MAIN_LAYOUT",FormSelectFactory.create("LAYOUT_TYPE").addSelectedValue(mainLayout));
		
		String currentTabId = (String)this.getSessionAttributes().get(MenuBarManageHandler.class.getName()+"currentTabId");
		if (StringUtil.isNullOrEmpty(currentTabId)){
			currentTabId = "base";
		}
		this.setAttribute("currentTabId",currentTabId);
	}
	protected String provideDefaultNodeId(DataParam param){
		return param.get("NAV_ID");
	}
	public ViewRenderer doSaveAction(DataParam param){
		String navigaterId = param.get("NAV_ID");
		String menuId = param.get("MENU_ID");
		String menuCode = param.get("MENU_CODE");
		
		boolean isCodeDuplicate = getService().isCodeDuplicate(navigaterId,menuId, menuCode);
		if (isCodeDuplicate){
			setErrorMsg("编码重复，请检查！");
			return prepareDisplay(param);
		}else{
			PortalConfigService portalConfigService = (PortalConfigService)this.lookupService("PortalConfigService");
			portalConfigService.refreshMenuBar(navigaterId);
			return super.doSaveAction(param);			
		}
	}	
	public ViewRenderer doMoveUpAction(DataParam param){
		PortalConfigService portalConfigService = (PortalConfigService)this.lookupService("PortalConfigService");
		String navigaterId = param.get("NAV_ID");
		portalConfigService.refreshMenuBar(navigaterId);
		return super.doMoveUpAction(param);
	}
	public ViewRenderer doMoveDownAction(DataParam param){
		PortalConfigService portalConfigService = (PortalConfigService)this.lookupService("PortalConfigService");
		String navigaterId = param.get("NAV_ID");
		portalConfigService.refreshMenuBar(navigaterId);
		return super.doMoveDownAction(param);
	}
	public ViewRenderer doDeleteAction(DataParam param){
		PortalConfigService portalConfigService = (PortalConfigService)this.lookupService("PortalConfigService");
		String navigaterId = param.get("NAV_ID");
		portalConfigService.refreshMenuBar(navigaterId);
		
		String nodeId = param.get(this.nodeIdField);
		List<DataRow> childRecords = getService().queryChildRecords(nodeId);
		if (ListUtil.isNullOrEmpty(childRecords)){
			String resourceId = param.get("MENU_ID");
			String resourceType = Resource.Type.Menu;
			boolean isExistSecurityRelation = isExistSecurityRelation(resourceId, resourceType);
			if (isExistSecurityRelation){
				this.setErrorMsg("该节点存在授权关联，先删除相关授权信息！");	
			}else{
				getService().deleteCurrentRecord(nodeId);
				param.remove(this.nodeIdField);
				param.put(this.nodeIdField,param.get(this.nodePIdField));				
			}
		}else{
			this.setErrorMsg(deleteErrorMsg);
		}
		return prepareDisplay(param);
	}	
	protected boolean isRootNode(DataParam param){
		String nodeId = getAttributeValue(this.nodeIdField);
		String navId = param.get("NAV_ID");
		return navId.equals(nodeId);
	}
	public ViewRenderer doBackAction(DataParam param){
		return new DispatchRenderer(getHandlerURL(NavigaterManageListHandler.class));
	}
	@PageAction
	public ViewRenderer isAlreadyExistSecurityRelation(DataParam param){
		String resourceId = param.get("menuId");
		String resourceType = Resource.Type.Menu;
		boolean isExistSecurityRelation = isExistSecurityRelation(resourceId, resourceType);
		if (isExistSecurityRelation){
			return new AjaxRenderer("Y");
		}
		return new AjaxRenderer("N");		
	}
	
	private boolean isExistSecurityRelation(String resourceId,String resourceType){
		boolean result = false;
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		List<DataRow> roleList = authorizationConfig.retrieveRoleList(resourceType, resourceId);
		if (roleList != null && roleList.size() > 0){
			result = true;
		}
		List<DataRow> userList = authorizationConfig.retrieveUserList(resourceType, resourceId);
		if (userList != null && userList.size() > 0){
			result = true;
		}
		List<DataRow> groupList = authorizationConfig.retrieveGroupList(resourceType, resourceId);
		if (groupList != null && groupList.size() > 0){
			result = true;
		}
		return result;
	}
	
	protected MenuBarManage getService(){
		return (MenuBarManage)this.lookupService(serviceId);
	}
}